package com.vegetable.modules.service.stock.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.utils.PageUtils;
import com.vegetable.modules.entity.baseData.Products;
import com.vegetable.modules.entity.baseData.ProductSpec;
import com.vegetable.modules.entity.stock.StockAlert;
import com.vegetable.modules.entity.stock.StockAlertRecord;
import com.vegetable.modules.entity.stock.po.StockAlertRecordQueryPO;
import com.vegetable.modules.mapper.stock.StockAlertRecordMapper;
import com.vegetable.modules.service.baseData.IProductSpecService;
import com.vegetable.modules.service.baseData.IProductsService;
import com.vegetable.modules.service.stock.IStockAlertRecordService;
import com.vegetable.modules.service.stock.IStockAlertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 库存预警记录表 服务实现类
 * </p>
 *
 * @author wangruijie
 * @since 2024-09-09
 */
@Slf4j
@Service
public class StockAlertRecordServiceImpl extends ServiceImpl<StockAlertRecordMapper, StockAlertRecord> implements IStockAlertRecordService {

    @Resource
    private StockAlertRecordMapper stockAlertRecordMapper;
    
    @Lazy
    @Resource
    private IStockAlertService stockAlertService;
    
    @Resource
    private IProductsService productsService;
    
    @Resource
    private IProductSpecService productSpecService;

    @Override
    public PageUtils queryPage(StockAlertRecordQueryPO po) {
        Page<StockAlertRecord> page = new Page<>(po.getPage(), po.getSize());
        IPage<StockAlertRecord> result = stockAlertRecordMapper.selectRecordPage(page, po);
        return new PageUtils(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StockAlertRecord createAlertRecord(Long alertId, Long commodityId, Long specsId, 
                                            Integer currentQuantity, Integer alertQuantity, Integer alertLevel) {
        log.info("创建库存预警记录，商品ID：{}，规格ID：{}，当前库存：{}，预警阈值：{}", 
               commodityId, specsId, currentQuantity, alertQuantity);
        
        // 查询商品信息
        Products product = productsService.getById(commodityId);
        if (ObjectUtil.isNull(product)) {
            throw new RuntimeException("商品不存在");
        }
        
        // 查询规格信息（如果有规格ID）
        ProductSpec productSpec = null;
        if (ObjectUtil.isNotNull(specsId)) {
            productSpec = productSpecService.getById(specsId);
        }
        
        StockAlertRecord record = new StockAlertRecord();
        record.setAlertId(alertId);
        record.setCommodityId(commodityId);
        record.setCommodityName(product.getCommonName());
        record.setCommonCode(product.getCommonCode());
        record.setSpecsId(specsId);
        if (ObjectUtil.isNotNull(productSpec)) {
            record.setSpecsName(productSpec.getName());
        }
        record.setCurrentQuantity(currentQuantity);
        record.setAlertQuantity(alertQuantity);
        record.setAlertLevel(alertLevel);
        record.setAlertStatus(0); // 未处理
        record.setAlertTime(new Date());
        record.setRegionId(product.getRegionId());
        
        save(record);
        return record;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleAlertRecord(Long recordId, Long handleUserId, String handleRemark, Integer alertStatus) {
        log.info("处理预警记录，记录ID：{}，处理人：{}，状态：{}", recordId, handleUserId, alertStatus);
        
        StockAlertRecord record = getById(recordId);
        if (ObjectUtil.isNull(record)) {
            throw new RuntimeException("预警记录不存在");
        }
        
        if (record.getAlertStatus() != 0) {
            throw new RuntimeException("该预警记录已被处理");
        }
        
        record.setAlertStatus(alertStatus);
        record.setHandleTime(new Date());
        record.setHandleUserId(handleUserId);
        if (StrUtil.isNotBlank(handleRemark)) {
            record.setHandleRemark(handleRemark);
        }
        
        return updateById(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchHandleAlertRecord(List<Long> recordIds, Long handleUserId, String handleRemark, Integer alertStatus) {
        if (CollectionUtil.isEmpty(recordIds)) {
            return false;
        }
        
        log.info("批量处理预警记录，记录数量：{}，处理人：{}，状态：{}", recordIds.size(), handleUserId, alertStatus);
        
        List<StockAlertRecord> records = recordIds.stream().map(recordId -> {
            StockAlertRecord record = new StockAlertRecord();
            record.setId(recordId);
            record.setAlertStatus(alertStatus);
            record.setHandleTime(new Date());
            record.setHandleUserId(handleUserId);
            if (StrUtil.isNotBlank(handleRemark)) {
                record.setHandleRemark(handleRemark);
            }
            return record;
        }).collect(Collectors.toList());
        
        return updateBatchById(records);
    }

    @Override
    public Long countUnhandledRecords() {
        return stockAlertRecordMapper.countUnhandledRecords();
    }

    @Override
    public StockAlertRecord getLatestAlertRecord(Long commodityId, Long specsId) {
        return stockAlertRecordMapper.selectLatestByCommodityAndSpecs(commodityId, specsId);
    }
}